/*
 * @lc app=leetcode.cn id=273 lang=typescript
 *
 * [273] 整数转换英文表示
 */

// @lc code=start
function numberToWords(num: number): string {
  if (num === 0) return 'Zero';

  const singles = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'];
  const teens = [
    'Ten',
    'Eleven',
    'Twelve',
    'Thirteen',
    'Fourteen',
    'Fifteen',
    'Sixteen',
    'Seventeen',
    'Eighteen',
    'Nineteen',
  ];
  const tens = [
    '',
    'Ten',
    'Twenty',
    'Thirty',
    'Forty',
    'Fifty',
    'Sixty',
    'Seventy',
    'Eighty',
    'Ninety',
  ];
  const thousands = ['', 'Thousand', 'Million', 'Billion'];

  const recursion = (curr: string[], num: number) => {
    if (num === 0) {
      return;
    } else if (num < 10) {
      curr.push(`${singles[num]}`);
    } else if (num < 20) {
      curr.push(`${teens[num - 10]}`);
    } else if (num < 100) {
      curr.push(`${tens[(num / 10) >> 0]}`);
      recursion(curr, num % 10);
    } else {
      curr.push(`${singles[(num / 100) >> 0]} Hundred`);
      recursion(curr, num % 100);
    }
  };

  let unit = 10 ** 9;
  const ans: string[] = [];
  // 从高位开始，3位数字一组开始转换
  for (let i = 3; i >= 0; i--, unit /= 10 ** 3) {
    const currNum = (num / unit) >> 0;
    if (currNum !== 0) {
      num -= currNum * unit;
      const curr: string[] = [];
      recursion(curr, currNum);
      curr.push(`${thousands[i]}`);
      ans.push(...curr);
    }
  }

  return ans.join(' ').trim();
}
// @lc code=end
